#import "Page1.h"
#import "MainView.h"
#import "HTTPProcessor.h"
#import "UIPreferencesTableButton.h"
#import <UIKit/UIPreferencesControlTableCell.h>
#import <UIKit/UIPreferencesDeleteTableCell.h> 

@implementation Page1
- (id)initWithFrame:(CGRect)rect processor:(HTTPProcessor *)_processor {
    if ((self == [super initWithFrame:rect]) != nil) {
		processor = _processor;
		[processor retain];

        [self setDataSource:self];
        [self setDelegate:self];
		[self createControls];
		dolog("page initiated");
	}

    return self;
} 

- (void)dealloc {
	int i;
	for(i = 0; i < [self preferencesTable:nil numberOfRowsInGroup:0]; i++) {
		[buttons[i] release];
	}
	[processor release];
    [self dealloc];
    [super dealloc];
}

- (void) createControls {
	int i;
	for(i = 0; i < 3; i++) {
	dolog("creating buttons %s %s", [[self titleForNumber:i] UTF8String], [[self cellForNumber:i] UTF8String]);
		buttons[i] = [[UIPreferencesTableButton alloc] init];
		[buttons[i] setTitle:[self titleForNumber:i + 1]];
		[buttons[i] setAlignment:2];	
		[buttons[i] setDelegate:self];
		NSString *cellData = [self cellForNumber:i + 1];
		[buttons[i] setCellData:cellData];
	}
}

- (void) refresh {
	[processor request:@"get-A1?get-A2?get-A3" delegate:self];
}

- (NSString *) cellLetter {
	return @"A";
}

- (NSString *) cellForNumber:(int)number {
	return [NSString stringWithFormat:@"%@%d", [self cellLetter], number];
}

- (NSString *) titleForNumber:(int)number {
	return [NSString stringWithFormat:@"Cell %@", [self cellForNumber:number]];
}

- (int)numberOfGroupsInPreferencesTable:(UIPreferencesTable *)aTable {
    /* Number of logical groups, including labels */
    return NUM_GROUPS;
}

 - (int)preferencesTable:(UIPreferencesTable *)aTable numberOfRowsInGroup:(int)group {
    switch (group) {
        case(0):
            return 3;
            break;
    }
}

- (NSString *) title {
	return @"Page1";
}

- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)aTable cellForGroup:(int)group {
     if (groupcell[group] != NULL)
         return groupcell[group];

     groupcell[group] = [ [ UIPreferencesTableCell alloc ] init ];
     switch (group) {
         case (0):
             [ groupcell[group] setTitle:[self title]];
             break;
     }
     return groupcell[group];
}

- (float)preferencesTable:(UIPreferencesTable *)aTable heightForRow:(int)row inGroup:(int)group withProposedHeight:(float)proposed {
    /* Return height for group titles */
    if (row == -1) {
        if (group < 2) {
            return 40;
		}
    }

    /* Segmented controls are larger than the others */
    if (group == 0 && row == 2) {
        return 55.0;
	}

    return proposed;
}

- (BOOL)preferencesTable:(UIPreferencesTable *)aTable isLabelGroup:(int)group {
    if (group == 2) {
        return YES;
	}
    return NO;
}

- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)aTable cellForRow:(int)row inGroup:(int)group {
    return buttons[row];
}

- (void) buttonPressed:(NSString *)cellData {
	NSString *value;
	int i;
	dolog("button pressed %s",[cellData UTF8String]);
	for(i = 0; i < 3; i++) {
		if ([[buttons[i] cellData] compare:cellData] == NSOrderedSame) {
			if ([[buttons[i] title] length] < 8) {
				[self refresh];
				return;
			}
			NSString *state = [[buttons[i] title] substringFromIndex:8];
			dolog("State: %s", [state UTF8String]);
			if ([state compare:@"ON"] == NSOrderedSame) {
				value = @"0";
			} else {
				value = @"1";
			}
		} 
	}
	dolog("request set");
	[processor requestSet:self cell:cellData value:value];
}

- (void) reply:(NSString *)reply {
	dolog("reply received:%s",[reply UTF8String]);
	NSArray *values = [reply componentsSeparatedByString:@"|"];
	int j;
	for(j = 0; j < [values count]; j++) {
		dolog("command: %s",[[values objectAtIndex:j] UTF8String]);
		NSArray *split = [[values objectAtIndex:j] componentsSeparatedByString:@"-"];
		if ([[split objectAtIndex:0] compare:@"OK"] == NSOrderedSame) {
			int i;
			for(i = 0; i < 3; i++) {
				if ([[[buttons[i] title] substringWithRange:NSMakeRange(5, 2)] compare:[split objectAtIndex:1]] == NSOrderedSame) {
//				if ([[buttons[i] cellData] compare:[split objectAtIndex:1]] == NSOrderedSame) {
					NSString *value = [split objectAtIndex:2];
					NSString *label;
					if ([@"1" compare:value] == NSOrderedSame) {
						label = @" ON";
					} else {
						label = @" OFF";
					}
					[buttons[i] setTitle:[[self titleForNumber:i + 1] stringByAppendingString:label]];
				}
			}
		}
	}
}

- (void) error:(NSString *)text {
	UIAlertSheet *alertSheet = [ [ UIAlertSheet alloc ]
		initWithFrame: CGRectMake(0, 200, 320, 240) ];
	[ alertSheet setTitle:@"Error:" ];
	[ alertSheet setBodyText: text ];
	[ alertSheet setDelegate: self ];
	[ alertSheet setAlertSheetStyle: 0 ];
	[ alertSheet addButtonWithTitle:@"OK" ];
	[ alertSheet presentSheetInView: self ];
}

- (void)alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
	[ sheet dismiss ];
}
@end
